package sunwin.yoms.web.comm;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import sunwin.yoms.web.comm.controllerAspect.AuthorityAspect;
import sunwin.yoms.web.comm.controllerAspect.LogAspect;
import sunwin.yoms.web.comm.controllerAspect.ShareDataAspect;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by mt on 2015/7/28.
 * 拦截器
 */
@Component
public class YomsHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private ShareDataAspect shareDataAspect;
    @Autowired
    private AuthorityAspect authorityAspect;
    @Autowired
    private LogAspect logAspect;

    /**
     * This implementation always returns <code>true</code>.
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //鉴权
        boolean isAuthority = authorityAspect.authentication(response, (HandlerMethod) handler);

        //记录日志
        logAspect.writeLog(response, (HandlerMethod) handler, isAuthority);

        return isAuthority;
    }

    /**
     * This implementation is empty.
     */
    public void postHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
        shareDataAspect.refactorModelAndView(request, (HandlerMethod) handler, modelAndView);
    }

    /**
     * This implementation is empty.
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //更新日志
        logAspect.updateLog(response, request, ex);
    }
}
